package udf;

import beans.SenSorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.Row;

public class udfTest1_ScalaFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        String filePath = "src/main/resources/sensor.txt";
        DataStreamSource<String> inputStream = env.readTextFile(filePath);

        //转换成POJO
        SingleOutputStreamOperator<SenSorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SenSorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        //将流转换成表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id,timeStamp as ts,temperature as temp");

        //自定义标量函数，求id的哈希值
        //需要在环境中注册UDF
        HashCode hashCode = new HashCode(20);
        tableEnv.registerFunction("hashCode", hashCode);
        //table API
        Table resultTable = sensorTable.select("id, ts, hashCode(id)");

        //SQL
        tableEnv.createTemporaryView("sensor", sensorTable);
        Table SQLResult = tableEnv.sqlQuery("select id,ts,hashCode(id) from sensor");

        tableEnv.toAppendStream(resultTable, Row.class).print("table");
        tableEnv.toAppendStream(SQLResult, Row.class).print("sql");
        env.execute();
    }

    //实现自定义的ScalarFunction
    public static class HashCode extends ScalarFunction {
        //这个是一个种子，随便给不给
        private int factor = 13;

        public HashCode(int factor) {
            this.factor = factor;
        }

        //输出的类型是按照自己的需求来自定义的，但是必须是public的，和方法名必须是eval
        public int eval(String str) {

            return str.hashCode() * factor;
        }
    }
}
